<template>
  <div class="appointment-container">
    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <!--      <el-form :inline="true" label-position="left" label-width="90px">-->
      <el-form :inline="true" label-position="left" >
        <el-row :gutter="10" class="filter-row">
          <el-col :span="5">
            <el-form-item label="联系人" class="compact-item">
              <el-input v-model="filters.contactName" placeholder="输入联系人姓名" clearable @input="applyFilters"/>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="服务类型">
              <el-select v-model="filters.serviceType" placeholder="请选择" clearable @change="applyFilters">
                <el-option label="普通陪诊" value="1"></el-option>
                <el-option label="检查陪诊" value="2"></el-option>
                <el-option label="儿童陪诊" value="3"></el-option>
                <el-option label="长者陪诊" value="4"></el-option>
                <el-option label="急诊陪诊" value="5"></el-option>
                <el-option label="术后陪诊" value="6"></el-option>
              </el-select>
            </el-form-item>
            <div class="selection-info" v-if="filters.serviceType">
              已选择：
              {{ serviceTypeLabel(filters.serviceType) }}
            </div>
          </el-col>

          <el-col :span="4">
            <el-form-item label="预约状态">
              <el-select v-model="filters.status" placeholder="请选择" clearable @change="applyFilters">
                <el-option label="待处理" value="pending"></el-option>
                <el-option label="已确认" value="confirmed"></el-option>
                <el-option label="已完成" value="completed"></el-option>
                <el-option label="已取消" value="cancelled"></el-option>
                <el-option label="已拒绝" value="rejected"></el-option>
              </el-select>
            </el-form-item>
            <div class="selection-info" v-if="filters.status">
              已选择：
              {{ statusText(filters.status) }}
            </div>
          </el-col>

          <el-col :span="3" style="text-align: right;">
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 预约卡片列表容器 -->
    <div class="appointments-list">
      <!-- 预约卡片列表 -->
      <el-card v-for="item in filteredAppointments" :key="item.id" class="appointment-card" shadow="hover">
        <template #header>
          <span>预约编号：{{ item.id }}</span>
        </template>
        <ul class="appointment-info">
          <li><strong>用户名Id：</strong>{{ item.userId }}</li>
          <li><strong>陪诊员Id：</strong>{{ item.escortId }}</li>
          <li><strong>服务类型Id：</strong>{{ item.serviceTypeId }}</li>
          <li><strong>预约时间：</strong>{{ item.appointmentTime }}</li>
          <li><strong>联系人姓名：</strong>{{ item.contactName }}</li>
          <li><strong>联系电话：</strong>{{ item.contactPhone }}</li>
          <li><strong>当前状态：</strong>
            <el-tag :type="statusTagType(item.status)">
              {{ statusText(item.status) }}
            </el-tag>
          </li>
        </ul>
        <!-- 操作按钮区域 -->
        <div class="action-buttons">
          <el-button type="success" size="small" @click="confirmAppointment(item)" :disabled="item.status !== 'pending'">接受预约</el-button>
          <el-button type="primary" size="small" @click="completeAppointment(item)" :disabled="item.status !== 'confirmed'">完成服务</el-button>
        </div>
      </el-card>

      <!-- 无数据提示 -->
      <div v-if="filteredAppointments.length === 0" class="no-data">
        <p>暂无匹配的预约信息</p>
      </div>
    </div>
  </div>
</template>

<script>import axios from "@/request/request.js";

export default {
  name: "AppointmentView",
  data() {
    return {
      appointments: [],
      filteredAppointments: [], // 存储筛选后的数据
      filters: {
        contactName: '',
        serviceType: '',
        status: '',
        dateRange: [] // 新增字段：日期范围 [startDate, endDate]
      }
    };
  },
  created() {
    this.fetchAppointments();
  },
  methods: {
    async fetchAppointments() {
      try {
        const res = await axios.get("/v1/escort/appointments", { withCredentials: true });
        if (res.data.state === 2000) {
          this.appointments = res.data.data || [];
          this.filteredAppointments = [...this.appointments]; // 初始加载全部数据
        } else {
          this.$message.error("获取预约信息失败");
        }
      } catch (error) {
        console.error("请求出错:", error);
        this.$message.error("网络错误");
      }
    },

    confirmAppointment(appointment) {
      this.$confirm("您确定要接受该预约吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.updateAppointmentStatus(appointment.id, "confirmed", "预约已接受");
      }).catch(() => {});
    },

    rejectAppointment(appointment) {
      this.$confirm("您确定要拒绝该预约吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.updateAppointmentStatus(appointment.id, "rejected", "预约已拒绝");
      }).catch(() => {});
    },

    completeAppointment(appointment) {
      this.$confirm("确认已完成该预约服务？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.updateAppointmentStatus(appointment.id, "completed", "服务已完成");
      }).catch(() => {});
    },

    async updateAppointmentStatus(id, status, successMsg) {
      try {
        const res = await axios.put("/v1/escort/status", { id, status });

        if (res.data.state === 2000) {
          this.$message.success(successMsg);
          const index = this.appointments.findIndex(item => item.id === id);
          if (index !== -1) {
            this.appointments[index].status = status;
            this.applyFilters(); // 更新后重新应用筛选
          }
        } else {
          this.$message.error("操作失败，请重试");
        }
      } catch (error) {
        console.error("更新状态出错:", error);
        this.$message.error("网络错误");
      }
    },

    // 返回标签样式类型
    statusTagType(status) {
      switch (status) {
        case "pending":
          return "info";
        case "confirmed":
          return "success";
        case "completed":
          return "";
        case "cancelled":
          return "warning";
        case "rejected":
          return "danger";
        default:
          return "";
      }
    },


    // 应用所有筛选条件
    applyFilters() {
      let result = [...this.appointments];

      // 按联系人姓名
      if (this.filters.contactName.trim()) {
        const keyword = this.filters.contactName.toLowerCase();
        result = result.filter(app =>
            app.contactName && app.contactName.toLowerCase().includes(keyword)
        );
      }

      // 按服务类型
      if (this.filters.serviceType) {
        result = result.filter(app => app.serviceTypeId === parseInt(this.filters.serviceType));
      }

      // 按状态
      if (this.filters.status) {
        result = result.filter(app => app.status === this.filters.status);
      }

      // 按日期范围
      if (this.filters.dateRange && this.filters.dateRange.length === 2) {
        const [startDate, endDate] = this.filters.dateRange;
        result = result.filter(app => {
          const appointmentDate = app.appointmentTime.split(' ')[0]; // 只取日期部分
          return appointmentDate >= startDate && appointmentDate <= endDate;
        });
      }

      this.filteredAppointments = result;
    },
    // 显示服务类型标签
    serviceTypeLabel(value) {
      const map = {
        '1': '普通陪诊',
        '2': '检查陪诊',
        '3': '儿童陪诊',
        '4': '长者陪诊',
        '5': '急诊陪诊',
        '6': '术后陪诊'
      };
      return map[value] || '';
    },

    // 复用已有 statusText 方法
    statusText(status) {
      return {
        pending: "待处理",
        confirmed: "已确认",
        completed: "已完成",
        cancelled: "已取消",
        rejected: "已拒绝"
      }[status] || status;
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        contactName: '',
        serviceType: '',
        status: '',
        dateRange: []
      };
      this.applyFilters(); // 重置后重新应用筛选
    }
  }
};
</script>

<style scoped>
.appointment-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background-color: #f0f9ff; /* 与 #c4e2fb 相近的浅色调作为背景 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.filter-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(196, 226, 251, 0.4); /* 使用 #c4e2fb 作为阴影色调来源 */
}

.appointments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.appointment-card {
  width: calc(33.33% - 20px); /* 默认三列 */
  min-width: 300px;
  max-width: 400px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(196, 226, 251, 0.4);
  transition: transform 0.2s ease; /* 添加过渡效果 */
}

.appointment-card:hover {
  transform: translateY(-5px); /* 鼠标悬停时的提升效果 */
}

/* 小屏设备：每行两列 */
@media (max-width: 1200px) {
  .appointment-card {
    width: calc(50% - 20px);
  }
}

/* 超小屏设备：每行一列 */
@media (max-width: 576px) {
  .appointment-card {
    width: 100%;
  }
}

.appointment-info {
  list-style: none;
  padding: 0;
  margin-bottom: 15px;
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 8px;
}

.appointment-info li {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
}

.appointment-info li strong {
  width: 100px;
  text-align: right;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: auto;
}

.no-data {
  text-align: center;
  color: #999;
  margin-top: 50px;
}
/* 标签宽度控制 */
.compact-item :deep(.el-form-item__label) {
  padding-right: 8px !important;
  width: 68px !important;
}

/* 输入框自适应 */
.compact-input :deep(.el-input__inner),
.compact-select :deep(.el-input__inner) {
  width: 100% !important;
  min-width: 120px; /* 保证最小可操作宽度 */
}

/* 日期选择器宽度优化 */
.compact-date :deep(.el-date-editor) {
  width: 240px !important;
}

.selection-info {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 8px;
  padding: 6px 12px;
  transition: background-color 0.2s ease, transform 0.2s ease;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--success:hover {
  background-color: #5cb82f;
  transform: translateY(-2px);
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f05c5c;
  transform: translateY(-2px);
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #3584e4;
  transform: translateY(-2px);
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
  padding: 4px 8px;
}

.el-tag--info {
  background-color: #c4e2fb; /* 使用 #c4e2fb 色系 */
  color: #333;
  border-color: #c4e2fb;
}

.el-tag--success {
  background-color: #67c23a;
  color: #fff;
  border-color: #67c23a;
}

.el-tag--warning {
  background-color: #e6a23c;
  color: #fff;
  border-color: #e6a23c;
}

.el-tag--danger {
  background-color: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
}

</style>
